package com.zq.common.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.same.SaSameUtil;
import cn.dev33.satoken.util.SaResult;
import com.zq.common.exception.ResultException;
import com.zq.common.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Sa-Token 权限认配置，内部系统的外网隔离
 */
@Configuration
//排除网关服务
@ConditionalOnClass(DispatcherServlet.class)
@Slf4j
public class SaTokenFilter implements WebMvcConfigurer {
    // 注册 Sa-Token 全局过滤器
    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                .addInclude("/**")
                .addExclude("/favicon.ico")
                .setAuth(obj -> {
                    // 校验是否由网关发出的请求 身份凭证
                    String header = SaHolder.getRequest().getHeader("sa-gateway");
                    if(header==null){
                        throw new ResultException(555,"没有经过网关");

                    }
                    if (!"zhangqiao".equals(header)){
                        throw new ResultException(555,"网关发布的凭证不对");
                    }
                })
                .setError(e -> Result.errorData(e.getMessage()))
                ;
    }
}

